from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from models.ChiTietDonHang import ChiTietDonHang
from models.DonHang import DonHang
from models.HangDatHomNay import HangDatHomNay
from models.HangHoa import HangHoa
from models.HoaHongNhanVien import HoaHongNhanVien
from models.KhachHang import KhachHang
from utils.Const import TrangThaiDonHang, LoaiNhanVien
from utils.permission_required import permission_required
import WSGI
import json as simplejson
import logging
import math
import webapp2
from google.appengine.ext import db

logger = logging.getLogger("GUIQuanLyDonHang")

class GuiQuanLyDonHang(webapp2.RequestHandler):
    priv = ''
    perm = 'KinhDoanh.QuanLyDonHang'
    @permission_required
    def get(self):
        if self.priv in ['Owner', 'Accounting']:
            cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        else:
            user = users.get_current_user()
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
            cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, nhanVien.key().id())
        for item in cbbTenNV:
            item['tenNV'] = str(item['id']) + ' - ' + item['tenNV']
        lstTenNVText = ''
        for item in cbbTenNV:
            #if item['codeLoaiNV'] == LoaiNhanVien.GIAO_HANG:
            lstTenNVText += str(item['id']) + ':' + item['tenNV'] + ';'
        lstTenNVText = lstTenNVText[:-1]
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        doanhThuThang = 0
        today = (dt.now() + datetime.timedelta(hours=7)).date()
        muc = 0
        hoaHong = 0
        
        if nv.codeLoaiNV == LoaiNhanVien.KINH_DOANH or nv.codeLoaiNV == LoaiNhanVien.CONG_TAC_VIEN:
            lstDonHang, _ = DaoQuanLyNhanVien.getListDonHang('', '1/' + str(today.month) + '/' + str(today.year), str(today.day) + '/' + str(today.month) + '/' + str(today.year), 10000, 0, nv.key().id(), '')
        
            for item in lstDonHang:
                doanhThuThang += item['tongTien']
        
            muc = DaoQuanLyNhanVien.getChiTieuKinhDoanh(nv.key().id())
            #tinh hoa hong
            hhQuery = HoaHongNhanVien.all().filter('maNV =', nv.key().id())
            hhQuery.order('nhoNhat')
            lstHoaHong = hhQuery.run()
            for item in lstHoaHong:
                if doanhThuThang > item.nhoNhat:
                    if doanhThuThang > item.lonNhat:
                        delta = (item.lonNhat - item.nhoNhat)*(item.hoaHong/100)
                        hoaHong += delta
                    else:
                        delta = (doanhThuThang - item.nhoNhat)*(item.hoaHong/100)
                        hoaHong += delta
                        break 
        
        
        template_values = {
                        'codeLoaiNV': nv.codeLoaiNV,
                        'doanhThuThang': doanhThuThang,
                        'muc': muc,
                        'hoaHong': hoaHong,
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'priv': self.priv,
                        'lstNhanVien': cbbTenNV,
                        'lstTenNVText':lstTenNVText,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/QuanLyDonHang.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    priv = ''
    perm = 'KinhDoanh.QuanLyDonHang'
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListDonHang': 'getListDonHang',
                       'updateDonHang': 'updateDonHang'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListDonHang(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        #maNV = self.request.get('maNV')
        maKhachHang = self.request.get('maKhachHang')
        tuNgay = self.request.get('tuNgay')
        denNgay = self.request.get('denNgay')
        ngayGiao = self.request.get('ngayGiao')
        maNV = self.request.get('maNV')
        if self.priv not in ['Owner', 'Accounting']:
            user = users.get_current_user()
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
            if maNV != '':
                selectedNhanVien = DaoQuanLyNhanVien.getNhanVienById(int(maNV))
                if selectedNhanVien.parentId != nhanVien.key().id() and selectedNhanVien.key().id() != nhanVien.key().id():
                    return 1
            else:
                maNV = nhanVien.key().id()
                
            
        rows, rowNum = DaoQuanLyNhanVien.getListDonHang(maKhachHang, tuNgay, denNgay, gridRowNum, int((pageNum-1)*gridRowNum), maNV, ngayGiao)
        for item in rows:
            item['nvDat'] = str(item['maNVDat']) + ' - ' + item['tenNVDat']
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def jobLikeFunc(self, idDonHang):
        lstHangHoa = []
        lstChiTietDonHang = []
        lstHangDatHomNay = []
        lstIdDonHang = []
        lstIdDonHang.append(idDonHang)
        lstDonHang = []
        
        for i in range(0, lstIdDonHang.__len__()/30 + 1):
            queryChiTietDonHang = ChiTietDonHang.all().filter('maDonHang in', lstIdDonHang[i*30: (i+1)*30]).run()
            for ctdh in queryChiTietDonHang:
                lstChiTietDonHang.append(ctdh)
                lstHangHoa.append(HangHoa.get_by_id(ctdh.maHang))
        
        for hh in lstHangHoa:
            hangDat = HangDatHomNay.all().filter('maHang =', hh.key().id()).filter('ngay =', (dt.now() + datetime.timedelta(hours=7)).date()).get()
            if hangDat is None:
                hangDat = HangDatHomNay()
                hangDat.maHang = hh.key().id()
                hangDat.tenHang = hh.tenHangHoa
                hangDat.soLuongTonKho = hh.soLuongTonKho
                hangDat.soLuongDat = 0.0
                hangDat.duTru = 0.0
                hangDat.ngay = (dt.now() + datetime.timedelta(hours=7)).date()
            for ctdh in lstChiTietDonHang:
                if ctdh.duTru == None:
                    ctdh.duTru = 0.0
                if ctdh.maHang == hangDat.maHang:
                    hangDat.soLuongDat += ctdh.soLuong
                    hangDat.duTru += ctdh.duTru
                    lstChiTietDonHang.remove(ctdh)
            hh.soLuongTonKho += hangDat.duTru
            if hangDat.duTru > 0:
                lstDonHang.append(hh)
            if hangDat.soLuongDat > 0 or hangDat.duTru > 0:
                lstHangDatHomNay.append(hangDat)
        lstDonHang += lstHangDatHomNay
        db.put(lstDonHang)
    
    def updateDonHang(self):
        idDh = self.request.get('id')
        dh = None
        if idDh != '_empty':
            dh = DonHang.get_by_id(int(idDh))
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper == 'del':
            return 1
        else:
            trangThai = str(self.request.get('trangThai').strip())
            
            if dh.trangThai != TrangThaiDonHang.DA_GIAO_HANG and trangThai == TrangThaiDonHang.DA_GIAO_HANG:
                doanhThu = DaoQuanLyNhanVien.getDoanhThuByMaKhachHangAndNgay(dh.maKH, (dt.now() + datetime.timedelta(hours=7)).date())
                
                doanhThu.doanhThu += dh.tongTien
                doanhThu.put()
                kh = KhachHang.get_by_id(dh.maKH)
                if kh.hanThanhToan is None or kh.hanThanhToan < dh.ngayThanhToan:
                    kh.hanThanhToan = dh.ngayThanhToan
                    
                if kh.congNo is None:
                    kh.congNo = dh.tongTien
                else:
                    kh.congNo += dh.tongTien
                kh.put()
            
            if self.priv == 'Owner':
                if dh.trangThai in [TrangThaiDonHang.KHOA, TrangThaiDonHang.DA_CO_HANG]:
                    if trangThai in [TrangThaiDonHang.KHOA, TrangThaiDonHang.DA_CO_HANG, TrangThaiDonHang.DA_GIAO_HANG, TrangThaiDonHang.KHONG_GIAO_HANG]:
                        dh.trangThai = trangThai
                else:
                    if dh.trangThai not in [TrangThaiDonHang.KHOA, TrangThaiDonHang.DA_CO_HANG, TrangThaiDonHang.DA_GIAO_HANG, TrangThaiDonHang.KHONG_GIAO_HANG] and trangThai == TrangThaiDonHang.KHOA:
                        dh.trangThai = trangThai
                        self.jobLikeFunc(dh.key().id())
                nguoiGiao = self.request.get('nguoiGiao')
                if nguoiGiao != '' and dh.duTru == False:
                    dh.maNVGiaoHang = int(nguoiGiao)
                    dh.tenNVGiaoHang = DaoQuanLyNhanVien.getNhanVienById(int(nguoiGiao)).tenNV
                else:
                    dh.maNVGiaoHang = None
                    dh.tenNVGiaoHang = None
            dh.ghiChu = self.request.get('ghiChu')
            
            user = users.get_current_user()
            nhanVien = DaoQuanLyNhanVien.getNhanVienByUsername(user.nickname())
            dh.nvThayDoi = str(nhanVien.key().id()) + ' - ' + nhanVien.tenNV
            
            
                
            if self.priv == 'Accounting':
                if self.request.get('tienDaThanhToan') != '':
#                    doanhThu = DaoQuanLyNhanVien.getDoanhThuByMaKhachHangAndNgay(dh.maKH, (dt.now() + datetime.timedelta(hours=7)).date())
                    delta = float(self.request.get('tienDaThanhToan')) - dh.tienDaThanhToan
#                    doanhThu.tongThu += delta
#                    doanhThu.put()
                    kh = KhachHang.get_by_id(dh.maKH)
                    kh.congNo -= delta
                    kh.put()
                    
                dh.tienDaThanhToan = float(self.request.get('tienDaThanhToan'))
                    
            DaoQuanLyNhanVien.createOrUpdateDonHang(dh)
            return 1